import { User } from '@/type'
import { ProjectConfig, setAxiosHeader } from '@/config'
import { defineStore } from 'pinia'

// defineStore 调用后返回一个函数，调用该函数获得 Store 实体
export const useUserStore = defineStore({
  // id: 必须的，在所有 Store 中唯一
  id: 'myUserStore',
  // state: 返回对象的函数
  state: () => ({
    user: {},
    isLogin: false
  }),
  actions: {
    login(user: User) {
      this.user = user
      this.isLogin = true
      setAxiosHeader(ProjectConfig.TOKEN_NAME, user.wxToken)
      sessionStorage.setItem(ProjectConfig.SESSION_IS_LOGIN, 'true')
      sessionStorage.setItem(ProjectConfig.SESSION_USER, JSON.stringify(user))
    },
    logout() {
      this.user = {}
      this.isLogin = false
      sessionStorage.removeItem(ProjectConfig.SESSION_IS_LOGIN)
      sessionStorage.removeItem(ProjectConfig.SESSION_USER)
    }
  },
  getters: {
    getUser(state): User {
      return state.user as User
    },
    hasLogin(state): boolean {
      return state.isLogin
    }
  }
})
